package binarysearch;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/22 18:27
 */
public class BinarySearchDemo4 {

    public static void main(String[] args) {
        int[] nums = {1,2,2,2,3,3,3,3,3,3,4,5,6};
        int i = binarySearchLast(nums, 3);
        System.out.println(i);
    }

    //要查找等于给定元素的最后一个元素，当且仅当nums[mid] == target && nums[mid + 1] != target时，才返回mid
    //否则，将left = mid + 1，继续进入循环进行二分查找
    public static int binarySearchLast(int[] nums,int target){

        int left = 0;
        int right = nums.length - 1;

        while (left <= right){
            int mid = left + (right - left) / 2;
            if(nums[mid] < target){ //target在mid的右边
                left = mid + 1;
            }else if(nums[mid] > target){ //target在mid的左边
                right = mid - 1;
            }else {
                if(mid < nums.length - 1 && nums[mid + 1] != target){
                    return mid;
                }
                left = mid + 1;
            }
        }
        return -1;
    }
}
